<script setup>
import LfTabs from '@/components/commonUI/LfTabs.vue'
import TopicSettingBase from './TopicSettingBase.vue'
import TopicSettingMember from './TopicSettingMember.vue'
import TopicSettingDiscuss from './TopicSettingDiscuss.vue'
import TopicSettingApply from './TopicSettingApply.vue'
import TopicSettingStyle from './TopicSettingStyle.vue'
import SettingTitle from './components/SettingTitle.vue'
import { postSaveTopicFile, getTopicFileList, deleteTopicFile } from '@/axios/api/file'
import { ElMessage, ElMessageBox, genFileId } from 'element-plus'
import { onMounted, ref } from 'vue'
import { getToken } from '@/utils/webStorage'
import { useRoute } from 'vue-router'
import {
  setTemplateStyle
} from '@/axios/api/topic'

const route = useRoute()
// 获取host.js中的FILE_URL
const FILE_URL = hosts.FILE_URL[import.meta.env.MODE]

const topicList = [
  { id: 1, name: '主题设置' },
  { id: 2, name: '成员管理' },
  { id: 3, name: '话题管理' },
  { id: 4, name: '加入主题版块验证' },
  { id: 5, name: '模板风格设置' },
  { id: 6, name: '文档管理' },
]

const activeIndex = ref(0)

const changeSubmitType = (index) => {
  activeIndex.value = index
}

const radio1 = ref('1')
const tableData = ref([
  {
    name: '文档1',
    address: '地址1',
  },
])

const topicId = ref(route.params.topicId)
const showDocDialog = ref(false)
const uploadFileList = ref([])
const fileList = ref([])
const fileLoading = ref(false)
const filePage = ref(1)
const fileLimit = ref(10)
const fileTotal = ref(0)
const uploadRef = ref(null)


const handleAdd = () => {
  showDocDialog.value = true
  uploadFileList.value = []
  // fileList.value = []
}

const handleSaveStyle = () => {
  setTemplateStyle({
    topicId: topicId.value,
    style: radio1.value
  }).then((res) => {
    if (res.code == 0) {
      ElMessage.success('保存成功')
    } else {
      ElMessage.error('保存失败')
    }
  })
}

const handleDialogClose = () => {
  showDocDialog.value = false
  uploadFileList.value = []
  // fileList.value = []
  // 清空上传组件的文件列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

const handleUploadSuccess = (response, file, fileListArr) => {
  console.log('response', response)
  if (response.code === 0 && response.result) {
    // 更新uploadFileList用于提交
    uploadFileList.value = [{
      fileName: file.name,
      filePath: response.result || '',
      fileSize: file.size,
      fileType: file.raw.type,
      topicId: topicId.value,
    }]
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

const handleExceed = (files, uploadFiles) => {
  // 清空之前的文件，只保留新选择的文件
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadRef.value.handleStart(file)
  }
}

const handleRemove = (file, uploadFiles) => {
  console.log('移除文件:', file, uploadFiles)
  // 同步清空uploadFileList
  uploadFileList.value = uploadFileList.value.filter(item => item.fileName !== file.name)
}

const beforeRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `确定要移除文件 ${uploadFile.name} 吗？`
  ).then(
    () => true,
    () => false
  )
}

const handleRemoveUpload = (idx) => {
  uploadFileList.value.splice(idx, 1)
}

const beforeUpload = (file) => {
  if (file.size > 50 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过50M')
    return false
  }
  return true
}

const handleDocDialogOk = async () => {
  if (!uploadFileList.value.length) {
    ElMessage.warning('请先上传文档')
    return
  }
  try {
    for (const file of uploadFileList.value) {
      await postSaveTopicFile(file)
    }
    ElMessage.success('保存成功')
    handleDialogClose()
    fetchFileList()
  } catch (e) {
    ElMessage.error('保存失败')
  }
}

const fetchFileList = async () => {
  try {
    const res = await getTopicFileList(topicId.value, filePage.value, fileLimit.value)
    if (res.code === 0 && res.result) {
      fileList.value = res.result.data || []
      fileTotal.value = res.result.total || 0
    }
  } catch (e) {
    fileList.value = []
  }
}

onMounted(() => {
  fetchFileList()
})

const handleDelete = async (file) => {
  try {
    await ElMessageBox.confirm('确定要删除该文档吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await deleteTopicFile(file.id)
    ElMessage.success('删除成功')
    fetchFileList()
  } catch (e) {
    if (e !== 'cancel' && e !== 'close') {
      ElMessage.error('删除失败')
    }
    // 用户取消不提示
  }
}
</script>

<template>
  <div class="p-8 px-[50px] flex flex-col h-full">
    <header class="text-3xl font-bold mb-[20px]">主题管理</header>

    <LfTabs :activeIndex="activeIndex" :tabOptions="topicList" :onTopicClick="changeSubmitType" />

    <TopicSettingBase v-if="activeIndex === 0" />
    <TopicSettingMember v-if="activeIndex === 1" />
    <TopicSettingDiscuss v-if="activeIndex === 2" />
    <TopicSettingApply v-if="activeIndex === 3" />
    <div v-if="activeIndex === 4">
      <SettingTitle title="模板风格" />
      <div class="mb-2">
        <el-radio-group v-model="radio1">
          <el-radio value="1" size="large">列表风格</el-radio>
          <el-radio value="2" size="large">卡片风格</el-radio>
        </el-radio-group>
      </div>
      <div class="flex justify-end items-center">
        <LfButton type="primary" @click="handleSaveStyle" class="my-4">保存模板风格</LfButton>
      </div>
    </div>
    <div v-if="activeIndex === 5">
      <div class="flex justify-end items-center">
        <LfButton type="primary" @click="handleAdd" class="my-4">添加文档</LfButton>
      </div>
      <el-card class="">
        <template #header>
          <div class="card-header">
            <span>文档管理</span>
          </div>
        </template>
        <div v-for="file in fileList" :key="file.fileName"
          class="text item flex justify-between my-2 border-1 border-[--line-1] rounded-md p-2">
          <div>
            <div>{{ file.fileName }}</div>
            <div class="text-xs text-gray-400">
              {{ file.fileType }} | {{ (file.fileSize / 1024 / 1024).toFixed(2) }}MB
            </div>
          </div>
          <el-button type="danger" @click="handleDelete(file)">删除</el-button>
        </div>
        <el-pagination v-if="fileTotal > fileLimit" class="mt-4" background layout="prev, pager, next"
          :total="fileTotal" :page-size="fileLimit" :current-page.sync="filePage" @current-change="fetchFileList" />
      </el-card>
      <el-dialog v-model="showDocDialog" title="上传文档" width="500px" :close-on-click-modal="false"
        @close="handleDialogClose">
        <el-upload ref="uploadRef" v-model:file-list="uploadFileList" class="upload-demo"
          :action="`${FILE_URL}/app/common/upload`" :before-upload="beforeUpload" :on-success="handleUploadSuccess"
          :on-remove="handleRemove" :before-remove="beforeRemove" :headers="{ token: getToken() || '' }" name="Image"
          :limit="1" :on-exceed="handleExceed" :auto-upload="true" :show-file-list="false">

          <el-button :disabled="uploadFileList.length >= 1" type="primary">选择文件</el-button>
          <!-- <template #tip>
            <div class="el-upload__tip">
              支持任意格式文件，大小不超过50MB，新文件将覆盖旧文件
            </div>
          </template> -->
        </el-upload>
        <div v-if="uploadFileList.length" class="mt-4">
          <div v-for="(file, idx) in uploadFileList" :key="file.fileName + idx"
            class="flex justify-between items-center border-b py-1">
            <span>{{ file.fileName }} ({{ (file.fileSize / 1024 / 1024).toFixed(2) }}MB)</span>
            <span class="text-xs text-gray-400">{{ file.fileType }}</span>
            <el-button type="danger" size="small" @click="handleRemoveUpload(idx)">移除</el-button>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleDialogClose">取消</el-button>
            <el-button type="primary" @click="handleDocDialogOk">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!-- <div v-if="activeIndex === 4"  class="cursor-pointer absolute top-0 right-0 border border-[--line-1] rounded-lg w-full h-full hover:border-[--line-b] hover:border-2"></div> -->
  </div>
</template>
